package controllerGoods

import (
	"github.com/gin-gonic/gin"
	goods_pb "mxshop/api/goods/v1"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	"mxshop/gmicro/pkg/common/core"
	translatorGin "mxshop/pkg/translator/gin"
	"net/http"
	"strconv"
)

type BrandFilter struct {
	Pages       int32    `form:"p" json:"p" binding:"required"`
	PagePerNums int32    `form:"n" json:"n" binding:"required"`
	OrderBy     []string `form:"o" json:"o" binding:"required"`
}

func (gc *GoodsController) BrandList(ctx *gin.Context) {
	var filter BrandFilter
	if err := ctx.ShouldBindQuery(&filter); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	rsp, err := gc.srv.Goods().Brand().BrandList(ctx, &goods_pb.BrandFilterRequest{
		Pages:       filter.Pages,
		PagePerNums: filter.PagePerNums,
		Orderby:     filter.OrderBy,
	})
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, rsp)
	return

}

func (gc *GoodsController) BrandDelete(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	if err := gc.srv.Goods().Brand().DeleteBrand(ctx, &dtoGoods.BrandDTO{
		Id: idInt,
	}); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}

func (gc *GoodsController) BrandNew(ctx *gin.Context) {
	brand := &dtoGoods.BrandDTO{}
	if err := ctx.ShouldBind(brand); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	rsp, err := gc.srv.Goods().Brand().CreateBrand(ctx, brand)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, &gin.H{
		"ID": rsp.Id,
	})
	return
}

func (gc *GoodsController) BrandUpdate(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	brand := &dtoGoods.BrandDTO{}
	if err := ctx.ShouldBind(brand); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	if err := gc.srv.Goods().Brand().UpdateBrand(ctx, &dtoGoods.BrandDTO{
		Id:   idInt,
		Name: brand.Name,
		Logo: brand.Logo,
	}); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}
